#include "jthread.h"
#include "jthread_p.h"

namespace JXQ
{

JThreadPrivate::JThreadPrivate(JThread *q_ptr) :
	q_ptr(q_ptr)
{

}

void JThreadPrivate::finish()
{
	m_condition.notify_all();

	if( m_ref > 1 )
		q_ptr->finished.send();

	if( m_deleteOnFinished )
	{
		delete q_ptr;
		delete this;
	}
	else if( not --m_ref )
		delete this;
}

JThread::JThread() :
	d_ptr(new JThreadPrivate(this))
{

}

bool JThread::wait(int msecs)
{
	std::unique_lock<std::mutex> locker(d_ptr->m_conditionMutex);
	if( msecs < 1 )
	{
		d_ptr->m_condition.wait(locker);
		return true;
	}
	return d_ptr->m_condition.wait_for(locker, std::chrono::milliseconds(msecs))
			!= std::cv_status::timeout;
}

void JThread::detach()
{
	d_ptr->m_isDetach = true;
}

void JThread::setEnableDeleteOnFinished(bool enable)
{
	d_ptr->m_deleteOnFinished = enable;
}

bool JThread::isEnableDeleteOnFinished() const
{
	return d_ptr->m_deleteOnFinished;
}

} //namespace JXQ
